package forum.dao.file;

import forum.entities.Post;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.math.BigInteger;

public class FilePostDAO extends FileGenericDAO<Post> {

    public FilePostDAO() {
        super("src\\main\\resources\\posts.xml","posts","post");
    }

    @Override
    protected Element mapEntityToElement(Document document, Element element, Post post) {
        Element postNode = document.createElement("post");
        element.appendChild(postNode);

        Node idNode = document.createElement("id");
        idNode.setTextContent(post.getId().toString());
        postNode.appendChild(idNode);

        Node postContainsNode = document.createElement("postContains");
        postContainsNode.setTextContent(post.getPostContains());
        postNode.appendChild(postContainsNode);

        Node topicIdNode = document.createElement("topicId");
        topicIdNode.setTextContent(post.getTopicId().toString());
        postNode.appendChild(topicIdNode);

        Node authorIdNode = document.createElement("authorId");
        authorIdNode.setTextContent(post.getAuthorId().toString());
        postNode.appendChild(authorIdNode);

        return postNode;
    }

    @Override
    protected Post mapElementToEntity(Document document, Element postNode) {
        NodeList childNodes = postNode.getChildNodes();
        Post post = new Post(new BigInteger(childNodes.item(0).getTextContent()));
        post.setPostContains(childNodes.item(1).getTextContent());
        post.setTopicId(new BigInteger(childNodes.item(2).getTextContent()));
        post.setAuthorId(new BigInteger(childNodes.item(3).getTextContent()));
        return post;
    }

    @Override
    protected Post newEntity() {
        return new Post(getNewKey());
    }
}
